import { hackRequestParams } from '~/utils/hack'

export function safeJsonParse(jsonStr: string) {
  try {
    const res = JSON.parse(jsonStr)
    return res || {}
  } catch (e) {
    return {}
  }
}

export function isDesktopUa() {
  const userAgent = navigator.userAgent.toLowerCase()
  // 判断是否是桌面浏览器，排除移动端设备
  return !/mobile|android|iphone|ipad|ipod/.test(userAgent)
}

export function safeJsonStringify(jsonData: object) {
  try {
    const res = JSON.stringify(jsonData)
    return res || '{}'
  } catch (e) {
    return '{}'
  }
}

export function useAsset(path: string): string {
  const assets = import.meta.glob('~/assets/images/**/*', {
    eager: true,
    import: 'default',
  })
  const filePath = `/assets/images/${path}`.replace(/\.png|\.jpe?g/, '.webp')
  // @ts-expect-error: wrong type info
  return assets[filePath] || assets[`${filePath}.webp`] || assets[`${filePath}.svg`]
}

export function isMobile() {
  var userAgent = navigator.userAgent || navigator.vendor || window['opera']
  return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent.toLowerCase())
}

export function fuckRequestParams(...args) {
  return hackRequestParams(...args)
}

export function roundToTwoDecimalPlaces(num) {
  return Math.round((num + Number.EPSILON) * 100) / 100
}

export function useSvg(path: string): string {
  const assets = import.meta.glob('~/assets/svg/**/*', {
    eager: true,
    import: 'default',
  })
  const filePath = `/assets/svg/${path}`
  // @ts-expect-error: wrong type info
  return assets[filePath] || assets[`${filePath}.svg`]
}

export function isIos() {
  let u = navigator.userAgent
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

export function isGateApp() {
  if (!process.client) return false
  return window.webkit?.messageHandlers?.gatepay || window.gateio?.gatepay
}

export const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export const validator = (val) => /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,12}$/.test(val)

export const chunk = (arr, size) => {
  let result = []
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size))
  }
  return result
}

export async function setBitId() {
  let bitId = localStorage.getItem('bit_local_id')
  if (bitId) return bitId
  bitId = Math.random().toFixed(32).slice(2)
  await import('~/utils/bitloader.js')
    .then(async (FingerprintJS) => {
      try {
        const fpPromise = FingerprintJS.load({
          apiKey: 'ofPWa5fQ6Y9UqyJ2EPHF',
          endpoint: 'https://metrics.xiao-haijing.com',
        })
        const { visitorId } = await fpPromise.then((fp) => fp.get())
        bitId = visitorId
        console.log('fp获取成功', bitId)
      } catch (e) {
        console.log('fp获取失败')
      }
    })
    .catch(() => {
      console.log('fp加载失败')
    })
  localStorage.setItem('bit_local_id', bitId)
  return bitId
}

export function initCrisp() {
  if (window.$crisp) return
  console.log('开始初始化crisp')
  window.$crisp = []
  window.CRISP_WEBSITE_ID = '7aed9bcd-7177-4dfc-940a-c07653e78958'
  window.$crisp.push([
    'on',
    'session:loaded',
    function () {
      console.log('初始化crisp')
      window.triggerCrispInit?.()
    },
  ])
  var d = document
  var s = d.createElement('script')
  s.src = 'https://client.crisp.chat/l.js'
  d.getElementsByTagName('head')[0].appendChild(s)
}
